// 连接mongodb
const mongoose = require('mongoose')
const { Schema } = mongoose

mongoose.connect('mongodb://localhost:27017/test', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})

const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function () {
  console.log('connected to mongodb')
})
// 定义schema
const userSchema = new Schema({
  name: String,
  age: Number,
  email: String,
  created_at: {
    type: Date,
    default: Date.now,
  },
})

// 定义model
const User = mongoose.model('User', userSchema)

// 创建文档
const user = new User({
  name: 'test',
  age: 18,
})
user.save(function (err) {
  if (err) return console.error(err)
  console.log('saved')
})
// 查询文档
User.find({}, function (err, users) {
  if (err) return console.error(err)
  console.log(users)
})
// 更新文档
User.updateOne({ name: 'test' }, { age: 20 }, function (err, res) {
  if (err) return console.error(err)
  console.log('updated')
})
// 删除文档
User.deleteOne({ name: 'test' }, function (err) {
  if (err) return console.error(err)
  console.log('deleted')
})
// 关闭连接
db.close()
